
//链接数据库  demo  ->  users


var express = require('express');
var router = express.Router();
var {  MongoClient, ObjectId } = require('mongodb');
const DBURL = "mongodb://localhost:27017";
const dbName = "demo";
const collectionName = "users";

 // 1：创建一个新的 MongoClient-db对象实例
let dbClient = new MongoClient(DBURL, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true 
});

// 2：链接数据库
let connectDB = ()=>{
    return  new Promise(async (resolve,reject)=>{
        try {
            // 连接mongodb服务器
          await  dbClient.connect()
          //   连接数据库
          let database = await  dbClient.db(dbName)
          console.log(database);
          resolve(database)

        } catch (error) {
            reject(error)
        }
    })
}

// connectDB().then(res=>{
//     console.log(res);
    
// })


// 3:添加数据操作
router.get('/useradd',async function(req, res) {
    console.log(req.query)
    let {name,age } = {"name":"tim",age:20}
    let db = await connectDB()
    console.log(db);
    try {
        await db.collection(collectionName).insertOne({ name, age });
        res.send({code: 200, msg: "添加成功" })
    } catch (error) {
        console.log("错误信息是：",error);
        res.send({code: 501, msg: "添加失败" })
    }
});

// 4.修改数据操作
router.get("/useredit", async (req, res) => {
    let { name, age } = req.query;
    let db = await connectDB();
    try {
      let filter = { name };
      let updateDoc = {
        $set: {
          age,
          name: "篮球",
        },
      };
      await db.collection(collectionName).updateOne(filter, updateDoc);
      res.send({ code: 200, msg: "修改成功" });
    } catch (error) {
      console.log("错误信息：", error);
      res.send({ code: 501, msg: "修改失败" });
    }
  });
  // 5.查看数据操作
  router.get("/userlist", async (req, res) => {
    let db = await connectDB();
    let query = { age: "20" };
    // let options = { _id: 1, name: 1 };
    try {
      let list = await db
        .collection(collectionName)
        // .find(query, options)
        .find(query)
        .limit(5)
        .sort({ _id: -1 })
        .toArray();
      res.send({ code: 200, msg: "查询成功", data: list });
    } catch (error) {
      console.log("错误信息：", error);
      res.send({ code: 501, msg: "查询失败" });
    }
  });
  // 6.删除数据操作
  router.get("/userremove", async (req, res) => {
    // let { name, age } = req.query;
    let { name, age } = {"name":"tim",age:20};
    let db = await connectDB();
    try {
      let filter = { name };
      await db.collection(collectionName).deleteOne(filter);
      res.send({ code: 200, msg: "删除成功" });
    } catch (error) {
      console.log("错误信息：", error);
      res.send({ code: 501, msg: "删除失败" });
    }
  });
  
  // 导出路由模块
  module.exports = router;